//
//  DatePickerView.m
//  NBANews
//
//  Created by Liccon Chang on 11-1-10.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "DatePickerView.h"


@implementation DatePickerView

@synthesize iShowDateLabel;
@synthesize Direction;

- (id)initWithFrame:(CGRect)frame showInControler:(UIViewController*) aController onComplete:(SEL)callback{
    if ((self = [super initWithFrame:frame])) {
		iController = aController;
		onCompleteSelectDate = callback;
		UIImageView* bgView = [[UIImageView alloc] initWithFrame:frame];
		[bgView setImage:[UIImage imageNamed:@"date.png"]];
		[self addSubview:bgView];
		[bgView release];
        iShowDateLabel = [[UILabel alloc] initWithFrame:frame];
		iShowDateLabel.backgroundColor = [UIColor clearColor];
		iShowDateLabel.textAlignment = UITextAlignmentCenter;
		[self setTextFromDate:[NSDate date]];
		Direction = 0;
		[self addSubview:iShowDateLabel];
    }
    return self;
}

- (void) setTextFromDate:(NSDate*) aDate{
	NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:@"yyyy-MM-dd"];
	iShowDateLabel.text = [formatter stringFromDate:aDate];
	[formatter release];
	if ([iController respondsToSelector:onCompleteSelectDate]) {
		[iController performSelector:onCompleteSelectDate withObject:self];
	}	
}

-(void)SelectDate{
	NSString *title = @"\n\n\n\n\n\n\n\n\n\n\n\n";
	if (Direction == 1)
		title =  @"\n\n\n\n\n\n\n\n\n"; 
	UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:title delegate:self cancelButtonTitle:@"确定" destructiveButtonTitle:nil otherButtonTitles:nil]; 
	if (iController.tabBarController.tabBar) {
		[actionSheet showFromTabBar:iController.tabBarController.tabBar];
	}
	else {
		[actionSheet showInView:iController.view];
	}
	
	UIDatePicker *datePicker = [[[UIDatePicker alloc] init] autorelease]; 
	datePicker.tag = 101;
	NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:@"yyyy-MM-dd"];
	if (iShowDateLabel.text != nil) {
		datePicker.date = [formatter dateFromString:iShowDateLabel.text];
	}
	[formatter release];
	datePicker.datePickerMode = 1;
	[actionSheet addSubview:datePicker]; 
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { 
	UIDatePicker *datePicker = (UIDatePicker *)[actionSheet viewWithTag:101]; 
	[self setTextFromDate:datePicker.date];
	[actionSheet release];
} 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
	[self SelectDate];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)dealloc {
	[iShowDateLabel release];
    [super dealloc];
}


@end
